<?php
class CategoriesController extends Controller
{
	public function addAction()
	{
		$model = new CategoriesModel();
		$this->save($model);
		$pid = $this->request->getParam('pid', 0);
		$this->view->options = $model->options(0, $pid);
	}
	
	public function editAction()
	{
		$model = $this->loadModel();
		$this->save($model);
		$this->view->options = $model->options(0, $model->category_pid);
	}
	
	public function listAction()
	{
		$do = $this->request->getPost('do');
		if (null !== $do)
		{
			$m = '';
			if (strcmp($do, 'status') === 0)
			{
				$model = $this->loadModel();
				$model->is_hide = $model->is_hide == 'y' ? 'n' : 'y';
				$model->save();
				$m = '已成功保存对该模型所作的修改：' . $model->category_name;
			}
			else if (strcmp($do, 'saveOrder') === 0)
			{
				$menu_orders = $this->request->getPost('menu_order');
				foreach ($menu_orders as $category_id => $menu_order)
				{
					$model = CategoriesModel::model()->findByPk($category_id);
					$model->menu_order = $menu_order;
					$model->save();
				}
				$m = '已成功保存对类别排序所作的修改';
			}
			else if (strcmp($do, 'delete') === 0)
			{
				$model = $this->loadModel();
				if ($model->countByAttributes(array('category_pid' => $model->category_id)) > 0)
					$m = '该类别拥有子类别，请先返回删除该类别下级类别。';
				else
				{
					// 省略代码, 将该类别下所有文档移至回收站.
					$m = '已成功删除一个类别：' . $model->category_name;
					$model->delete();
				}
			}
			
			$this->forward(array('m' => $m));
		}
		
		$models = array();
		$css = array();
		CategoriesModel::model()->lists(0, -1, $models, $css);
		$this->view->models = $models;
		$this->view->css = $css;
	}
	
	protected function save($model)
	{
		if ($attributes = $this->request->getPost('categories'))
		{
			if (CControllerConfig::getAction() == 'edit' && $model->category_name == $attributes['category_name'])
				$model->rules['category_name']['when'] = CModel::INSERT;
			
			$model->attributes = $attributes;
			if ($model->save())
			{
				$params = array(
					'id' => $model->pk,
					'm' => '已成功保存对该类别所作的修改：' . $model->category_name, 
					't' => self::T_MESSAGE
				);
				$do = $this->request->getPost('do', 'save');
				if (strcmp($do, 'save') === 0)
					$this->forward($params, 'list');
				else 
					$this->forward($params, 'edit');
			}
			else
			{
				$_GET['m'] = '无法保存该类别的信息：' . $model->getError();
				$_GET['t'] = self::T_ERROR;
			}
		}
		
		$this->view->model = $model;
		$this->view->modules = ModulesModel::model()->findAll();
	}
}
